import { ref, watch } from 'vue'
import { isEmpty } from '@/utils/util'

const breakpointsConfigDefault = [
  [513, 24, 'top'],
  [701, 12, 'top'],
  [1062, 8, 'right'],
  [1352, 8, 'right'],
  [Infinity, 6, 'right'],
]
const getSpanConfig = (width, span, labelPosition, gutter = 16) => {
  if (span && typeof span === 'number') {
    return {
      span,
      labelPosition,
    }
  }

  const spanConfig = !isEmpty(span) ? span : breakpointsConfigDefault
  let breakPoint = [undefined, 8, labelPosition]

  for (const entry of spanConfig) {
    if (width < entry[0] + gutter) {
      breakPoint = entry
      break
    }
  }
  return {
    span: breakPoint[1],
    labelPosition: breakPoint[2],
  }
}

export function useSpanConfig(width, span, labelPosition, gutter) {
  const formContext = ref({ span: 8, labelPosition: labelPosition })

  watch(width, () => {
    const spanConfig = getSpanConfig(width.value, span, labelPosition, gutter)
    Object.assign(formContext.value, spanConfig)
  })

  return formContext
}
